%%%====================================================================
%%% File    : pipe_console.erl
%%% Author  :  <vjache>
%%% Description: This is a simpliest pipe implementation. It may be 
%%%				 considered as a simple reference implementation of 
%%%				 a pipe callback module, and could be used for debug 
%%%				 purposes.
%%%
%%% Created : 09.07.2009
%%%====================================================================

-module(pipe_ets_insert).

%%
%% Include files
%%
-include("../include/pipe.hrl").
-include("../include/util.hrl").
%%
%% Exported Functions
%%
-export([
		 new/1,
		 new/2,
		 new/3,
		 open/1,
		 push/2,
		 flush/1,
		 close/1,
		 test/1]).

%%====================================================================
%% API Functions
%%====================================================================

new(Ets) ->
	new(Ets,1000).
new(Ets,BuffSize) ->
	new(Ets,BuffSize,pipe:terminator()).
new(Ets,BuffSize,NextPipe) ->
	pipe:pipe_from_module(?MODULE, {Ets,BuffSize}, NextPipe).

open({{Ets,BuffSize},NextPipe}) -> %%PipeState
    {Ets,BuffSize,[],pipe:open(NextPipe)}.
push({_Ets,0,_Buff,_NextPipeState}=S,Item) ->
	push(flush(S),Item);
push({Ets,BuffSize,Buff,NextPipeState},Item) 
  when is_tuple(Item) ->
    {Ets,BuffSize-1,
	 [Item|Buff],pipe:push(NextPipeState,Item)}.
flush({Ets,BuffSize,Buff,NextPipeState}) ->
	ets:insert(Ets, Buff),
	{Ets,BuffSize+length(Buff),[],NextPipeState}.
close(_S) ->
	ok.

%%====================================================================
%% Test Functions
%%====================================================================

test(L) ->
	S=pipe:open(new(ets:new(test, [bag]))),
	{IterState,PipeState}=pipe:push_each(S, iter:from_list(L)),
	iter:close(IterState),
	pipe:close(PipeState).


%%====================================================================
%% Local Functions
%%====================================================================



